package com.example.text4;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.IBinder;

import java.util.List;

public class PlayService extends Service {
    int cur_pos;
    List<Data> list;
    private MediaPlayer mediaPlayer;

    public PlayService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        list = MainActivity.getMusic(this);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) { //歌曲播放结束执行事件
                next();
            }
        });
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");

        if ("play".equals(action)) {
            cur_pos = intent.getIntExtra("pos", 0);
            play(cur_pos);
        } else if ("next".equals(action)) {
            next();
        } else if ("previous".equals(action)) {
            previous();
        } else if ("pause".equals(action)) {
            pause();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void play(int position) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(list.get(position).getUrl());
            mediaPlayer.prepare();
            mediaPlayer.start();
            cur_pos = position;
            Intent intent = new Intent("musicchange");
            intent.putExtra("pos", cur_pos);
            sendBroadcast(intent);
        } catch (Exception e) {

        }
    }

    public void pause() {
        Intent intent = new Intent("playpause");
        intent.putExtra("playing", mediaPlayer.isPlaying());
        sendBroadcast(intent);
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }
    }

    public void previous() {
        cur_pos--;
        if (cur_pos < 0) cur_pos = list.size() - 1;
        play(cur_pos);
    }

    public void next() {
        cur_pos++;
        if (cur_pos > list.size() - 1) cur_pos = 0;
        play(cur_pos);
    }
}